import { PlusOutlined } from '@ant-design/icons';
import {
  type ActionType,
  ModalForm,
  type ProColumns,
  ProFormDigit,
  ProFormGroup,
  ProTable,
  ProFormSelect
} from '@ant-design/pro-components';
import {Button, Descriptions, message, Tag} from 'antd';
import React, { useEffect, useRef, useState } from "react";
import {
  ProForm,
  ProFormText,
  ProFormList,
} from '@ant-design/pro-components';
import { addMaterialUsagePlan, listMaterialUsagePlanVoByPage, getMaterialUsagePlanDetailsById, approvalMaterialUsagePlan } from "@/services/materialUsagePlan/api";
import { MaterialUsagePlanVo, MaterialPlanAddDto,  MaterialUsagePlanDetailsVo } from "@/services/materialUsagePlan/typings";
import { getWarehouseList } from "@/services/warehouse/api";
import {generateTransferOrderByPlan} from "@/services/transfer/api";
import {useAccess} from "umi";

const MaterialUsagePlanApprovalForm: React.FC<{ open: boolean; onCancel: () => void; planId: string }> = (props) => {
  const [data, setData] = useState<MaterialUsagePlanDetailsVo>({});
  const [warehouseList, setWarehouseList] = useState<any[]>([]); // 存储仓库列表
  const [sourceWarehouse, setSourceWarehouse] = useState<string>(''); // 选择的源仓库
  const loadData = async () => {
    if (props.planId.length <= 0) {
      return;
    }
    const res = await getMaterialUsagePlanDetailsById({ id: props.planId });
    if (res.code != 0) {
      message.error("用料计划详情加载失败" + res.message);
      return;
    }
    setData(res?.data || {});
  }

  const loadWarehouseList = async () => {
    const res = await getWarehouseList();
    if (res.code === 0) {
      setWarehouseList(res.data || []);
    } else {
      message.error("仓库列表加载失败" + res.message);
    }
  }

  const handleApproval = async () => {
    const res = await approvalMaterialUsagePlan(props.planId );
    if (res.code != 0 || res.data == false) {
      message.error("用料计划审批失败" + res.message);
      return;
    }
    message.success("用料计划审批成功");
    props.onCancel();
  }

  const handleCreateTransfer = async () => {
    if (!sourceWarehouse) {
      message.error("请选择源仓库");
      return;
    }
    const res = await generateTransferOrderByPlan(sourceWarehouse, data?.warehouseId||"", props.planId);
    if (res.code === 0) {
      message.success("调拨单创建成功");
    } else {
      message.error("调拨单创建失败" + res.message);
    }
  }

  useEffect(() => {
    loadData();
    loadWarehouseList();
  }, [props.planId,]);

  return (
    <ModalForm
      layout="vertical"
      open={props.open}
      onFinish={async () => {
        await handleApproval();
      }}
      submitter={{
        searchConfig: {
          submitText: '审批'
        },
        render: (_, dom) => <div style={{ textAlign: 'center' }}>{dom}</div>,
      }}
      modalProps={
        {
          destroyOnClose: true,
          onCancel: props.onCancel,
        }
      }
    >
      <Descriptions title="用料计划明细 " bordered>
        <Descriptions.Item label="用料计划编号">{data.planNo}</Descriptions.Item>
        <Descriptions.Item label="仓库名">{data.warehouseName}</Descriptions.Item>
        <Descriptions.Item label="仓库代码">{data.warehouseCode}</Descriptions.Item>
        {data?.details?.map((item, index) => (
          <>
            <Descriptions.Item label="货品代码">{item.goodsCode}</Descriptions.Item>
            <Descriptions.Item label="名称">{item.goodsName}</Descriptions.Item>
            <Descriptions.Item label="数量">{item.quantity}</Descriptions.Item>
          </>
        ))}
      </Descriptions>
      {data.status==0&&<>
        <ProForm.Group>
          <ProFormSelect
            label="源仓库"
            width={"md"}
            name="sourceWarehouse"
            options={warehouseList.map(warehouse => ({
              label: warehouse.warehouseName,
              value: warehouse.id
            }))}
            onChange={(value: string) => setSourceWarehouse(value)}
          />
          <Descriptions bordered>
            <Descriptions.Item label="目标仓库">{data?.warehouseName}</Descriptions.Item>
          </Descriptions>
        </ProForm.Group>
        <Button type="primary" onClick={handleCreateTransfer}>
          创建调拨单
        </Button>
      </>}

    </ModalForm>
  );
};


type MaterialUsagePlanFormProps = {
  open: boolean;
  onCancel: () => void;
}


const MaterialUsagePlanForm: React.FC<MaterialUsagePlanFormProps> = (props) => {
  const handleCreate = async (values: MaterialPlanAddDto) => {
    const res = await addMaterialUsagePlan(values);
    if (res.code !== 0 || res.data !== true) {
      message.error("用料计划创建失败" + res.message);
      return;
    }
    message.success("用料计划创建成功");
    props.onCancel();
  }

  return (
    <ModalForm<MaterialPlanAddDto>
      layout="vertical"
      open={props.open}
      onFinish={async (values) => {
        await handleCreate(values);
      }}
      submitter={{
        render: (_, dom) => <div style={{ textAlign: 'center' }}>{dom}</div>,
      }}
      modalProps={{
        destroyOnClose: true,
        onCancel: props.onCancel,
      }}
    >
      {/* 主单信息 */}
      <ProForm.Group>
        <ProFormText
          name="planNo"
          label="用料计划编号"
          width="md"
          rules={[{ required: true, message: '请输入用料计划编号' }]}
        />
        <ProFormText
          name="warehouseNo"
          label="仓库编号"
          width="md"
          rules={[{ required: true, message: '请输入仓库编号' }]}
        />
      </ProForm.Group>

      {/* 动态子单列表 */}
      <ProFormList
        name="planDetails"
        creatorButtonProps={{
          creatorButtonText: '添加用料计划明细',
          style: { width: '200px' },
        }}
        itemRender={({ listDom, action }, { index }) => (
          <div
            style={{
              position: 'relative',
              padding: 24,
              border: '1px solid #eee',
              marginBottom: 24,
            }}
          >
            {listDom}
            <div style={{ position: 'absolute', top: 8, right: 8 }}>
              {action}
            </div>
          </div>
        )}
      >
        <ProFormGroup>
          <ProFormText name='planDetailNo' label='用料计划明细编号' required={true} />
          <ProFormText name='goodsNo' label='货品编码' required={true} />
          <ProFormText name='goodsName' label='货品名称' />
          <ProFormDigit name='num' label='数量' required={true} initialValue={0} />
        </ProFormGroup>
      </ProFormList>
    </ModalForm>
  );
};





const MaterialUsagePlanAdd: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [isCreate, setIsCreate] = useState<boolean>(false);
  const [isApproval, setIsApproval] = useState<boolean>(false);
  const [planId, setPlanId] = useState<string>('');
  const [data, setData] = useState<MaterialUsagePlanVo[]>([]);
  const [total, setTotal] = useState<number>(0);
  const access = useAccess();
  // @ts-ignore
  const columns: ProColumns<MaterialUsagePlanVo>[] = [
    {
      title: '仓库名称',
      width: 120,
      dataIndex: 'warehouseName',
    },
    {
      title: '用料计划编号',
      width: 120,
      dataIndex: 'planNo',
    },
    {
      title: '状态',
      width: 120,
      hideInSearch: true,
      //@ts-ignore
      render: (text, record) => {
        switch (record?.status) {
          case 90:
            return <Tag color="#2db7f5">已完成</Tag>;
          case 45:
            return <Tag color="yellow">已处理</Tag>;
          case 0:
            return <Tag color="red">未处理</Tag>;
          default:
            return null;
        }
      },
      dataIndex: 'status',
    },
    {
      title: '创建时间',
      width: 120,
      hideInSearch: true,
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 120,
      key: 'option',
      render: (text, record, _, action) => [
        <>{record?.status != 90 && access.admin && <Button
          key="approval"
          onClick={() => {
            setIsApproval(true);
            setPlanId(record?.id || '');
          }}
          type="primary"
        >
          审批
        </Button>}</>,
      ],
    }
  ];
  const loadData = async (params: any) => {
    const res = await listMaterialUsagePlanVoByPage({
      params: params,
      pageNum: currentPage,
      pageSize: 10,
    });
    if (res.code !== 0) {
      message.error("用料计划数据加载失败 " + res.message);
      return;
    }
    setData(res?.data?.records || []);
    setTotal(res?.data?.total || 0);
  }

  useEffect(() => {
    loadData({});
  }, [currentPage]);

  return (
    <>
      <ProTable<MaterialUsagePlanVo>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        dataSource={data}
        request={async (params) => {
          await loadData(params);
          return data;
        }}
        editable={{
          type: 'multiple',
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        pagination={{
          pageSize: 10,
          onChange: (page) => setCurrentPage(page),
          total: total,
        }}
        headerTitle="用料计划"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setIsCreate(true);
            }}
            type="primary"
          >
            用料计划创建
          </Button>,
        ]}
      />
      <MaterialUsagePlanForm
        onCancel={() => setIsCreate(false)}
        open={isCreate}
      />
      <MaterialUsagePlanApprovalForm
        onCancel={() => setIsApproval(false)}
        open={isApproval}
        planId={planId}
      />
    </>
  )
}

export default MaterialUsagePlanAdd;
